package logic

import (
	"context"
	"fmt"
	"vip-shop/Pkg"
	"vip-shop/cache"
	"vip-shop/model"

	"vip-shop/shoprpc/internal/svc"
	"vip-shop/shoprpc/shoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadLogic {
	return &UploadLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UploadLogic) Upload(in *shoprpc.UploadRequest) (*shoprpc.UploadResponse, error) {
	// todo: add your logic here and delete this line

	var user model.User
	model.DB.Debug().Where("tel=?", in.Tel).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("当前账号未注册")
	}
	c, _ := cache.Rdb.Get(l.ctx, "captCha"+in.Tel).Result()
	if c != in.Captcha {
		return nil, fmt.Errorf("图形验证码错误，请重新输入")
	}

	s, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.Tel).Result()
	if s != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}
	if in.Password != in.NewPassword {
		return nil, fmt.Errorf("两次密码不一致，请重新输入")
	}
	if user.Password == Pkg.Md5Str(in.Password) {
		return nil, fmt.Errorf("新密码与旧密码一致,请重新输入")
	}
	user.Password = Pkg.Md5Str(in.Password)
	return &shoprpc.UploadResponse{
		Id: int64(user.ID),
	}, nil
}
